package com.portal.sso.ldap.service;

import com.portal.sso.core.server.PortalUserServer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.util.Properties;
@Slf4j
@AllArgsConstructor
public class PortalSsoLdapServer implements PortalUserServer {
    PortalSsoLdapProperties portalSsoLdapProperties;
    /**
     * 验证用户登录
     *
     * @param userID
     * @param password
     *            String
     * @return boolean
     */
    private boolean authenticate(String userID, String password) {
        if (password != null && !"".equals(password.trim())) {
            DirContext ctx1;
            try {
                String domain = portalSsoLdapProperties.getDomain();
                Properties ldapEnv = new Properties();
                ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,
                        portalSsoLdapProperties.getInitial());
                //服务器必须配置DNS，否则无法解析ProviderUrl
                ldapEnv.put(Context.PROVIDER_URL, portalSsoLdapProperties.getProviderUrl());
                ldapEnv.put(Context.SECURITY_AUTHENTICATION, portalSsoLdapProperties.getAuthentication());
                String user = userID.indexOf(domain) > 0 ? userID : userID
                        + domain;
                ldapEnv.put(Context.SECURITY_PRINCIPAL, user);
                ldapEnv.put(Context.SECURITY_CREDENTIALS, password);
                ctx1 = new InitialDirContext(ldapEnv);
                ctx1.close();
                return true;
            } catch (AuthenticationException e) {
               log.error("登录失败！",e);
                return false;
            } catch (NamingException e) {
                log.error(e.getMessage(),e);
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public boolean Verification(String userId, String pwd) {
        return authenticate(userId,pwd);
    }
}
